package com.linfeng.component.oauth2.config;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableResourceServer;
import org.springframework.security.oauth2.config.annotation.web.configuration.ResourceServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configurers.ResourceServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.token.RemoteTokenServices;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;

import java.util.List;

@Slf4j
@Configuration
@EnableResourceServer
@RefreshScope
@Data
public class ResourceServerConfig extends ResourceServerConfigurerAdapter {

    @Value(value = "${oauth2.url.authenticated:/api/**}")
    private List<String> authenticatedUrl;

    @Value(value = "${oauth2.url.permit:/domain/**}")
    private List<String> permitUrl;

    @Value(value = "${oauth2.token.check.address:http://localhost:9006/server-oauth}")
    private String tokenCheckAddress;

    public static final String TOKEN_CHECK_PATH = "/oauth/check_token";

    @Value(value = "${oauth2.client_id:web}")
    private String clientId;

    @Value(value = "${oauth2.client_secret:654321}")
    private String clientSecret;

    /**
     * token服务配置
     */
    @Override
    public void configure(ResourceServerSecurityConfigurer resources) throws Exception {
        resources.tokenServices(tokenServices());
    }

    /**
     * 路由安全认证配置
     */
    @Override
    public void configure(HttpSecurity http) throws Exception {
        log.info("authenticatedUrl---->{}----permitUrl---->{}", authenticatedUrl, permitUrl);

        http.authorizeRequests()
                // 配置/api打头的路由需要安全认证，/domain配置无需认证
                .antMatchers(authenticatedUrl.toArray(new String[]{})).authenticated()
                .antMatchers(permitUrl.toArray(new String[]{})).permitAll()
                .and().csrf().disable();
    }


    /**
     * 资源服务令牌解析服务
     */
    @Bean
    @Primary
    public ResourceServerTokenServices tokenServices() {

        log.info("CheckTokenEndpointUrl---->{}{}", tokenCheckAddress, TOKEN_CHECK_PATH);
        RemoteTokenServices remoteTokenServices = new RemoteTokenServices();
        remoteTokenServices.setCheckTokenEndpointUrl(tokenCheckAddress + TOKEN_CHECK_PATH);
        remoteTokenServices.setClientId(clientId);
        remoteTokenServices.setClientSecret(clientSecret);
        return remoteTokenServices;
    }
}
